<script setup>
import { ref, reactive, onMounted, watch, computed } from 'vue';
import {
    reqPublicClassOption,
    reqPublicClassTimeOption,
    reqAddPublicClassNote
} from '@/api/teacher/record/publicClass';
import { useTeacherStore } from '@/stores/modules/teacherStore.js';
import { showFailToast, showSuccessToast, showNotify } from 'vant';

import router from '@/router';

const teacherStore = useTeacherStore();

const formRef = ref();

// date表单的验证方法
const validateDate = (rule, value, callback) => {
    const inputDate = new Date(value);
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    if (inputDate < today) {
        callback(new Error('不能预约过去的日期'));
    } else {
        callback();
    }
};

const formRule = reactive({
    class: [{ required: true, message: '请选择公共教室', trigger: 'change' }],
    date: [{ validator: validateDate, trigger: 'change' }],
    time: [
        {
            type: 'array',
            required: true,
            message: '请选择具体时间',
            trigger: 'change'
        }
    ],
    purpose: [{ required: true, message: '需要填写具体用途', trigger: 'blur' }]
});

const publicClassNote = reactive({
    class: '',
    date: '',
    time: '',
    peopleTotal: 1,
    classTotal: 1,
    purpose: ''
});

// 是否显示dailog
const isShowDialog = ref(false);

// 教室选项
const classOption = ref([]);

// 时间选项 (随着教室和日期的改变而改变)
const timeOption = ref([]);

// 时间表单是否进行
const timeInputDisabled = computed(
    () => !publicClassNote.class || !publicClassNote.date
);

// 时间表单的placeholder
const timeInputPlaceholder = computed(() => {
    if (!publicClassNote.class) {
        return '需要先选择班级';
    } else if (!publicClassNote.date) {
        return '需要先选择日期';
    } else {
        return '请选择时间';
    }
});

// 点击提交申请按钮,但是并不添加,添加方法请看comfirm
const submit = async formEl => {
    if (!formEl) return;
    await formEl.validate(valid => {
        if (valid) {
            isShowDialog.value = true;
        }
    });
};

// dialog中的确定按钮,点击申请公共教室预约
const confirm = async () => {
    try {
        const result = await reqAddPublicClassNote({
            day: publicClassNote.date,
            timeBucket: publicClassNote.time.join(','),
            classroomInfo: publicClassNote.class,
            specificApplications: publicClassNote.purpose,
            useDepartment: publicClassNote.class,
            people: publicClassNote.peopleTotal,
            classroomQuantity: publicClassNote.classTotal
        });
        if (result.status == 200) {
            isShowDialog.value = false;
            showSuccessToast({
                message: '发送成功, 3秒后返回主页',
                duration: 3000,
                zIndex: 1000,
            });
            setTimeout(() => router.push({ name: 'reservation-index' }), 3000);
        } else {
            throw new Error(result.statusText);
        }
    } catch (e) {
        isShowDialog.value = false;
        showFailToast({
            message: e.message || '发送失败',
            duration: 3000,
            zIndex: 100
        });
    }
};

watch(
    () => publicClassNote.class,
    () => {
        publicClassNote.date = '';
        publicClassNote.time = '';
        timeOption.value = [];
    }
);

// 获取教室选项
const getClassOption = async () => {
    try {
        const result = await reqPublicClassOption();
        if (result.status == 200) {
            classOption.value = result.dataList;
        } else {
            throw new Error(result.message || '公共教室信息获取失败');
        }
    } catch (e) {
        showFailToast(e.message || '公共教室信息获取失败');
    }
};

watch(
    () => publicClassNote.date,
    () => {
        publicClassNote.time = '';
        if (publicClassNote.date && publicClassNote.class) {
            const inputDate = new Date(publicClassNote.date);
            const today = new Date();
            today.setHours(0, 0, 0, 0);
            if (inputDate >= today) {
                getTimeOption();
            }
        }
    }
);

// 获取时间选项
const getTimeOption = async () => {
    try {
        const result = await reqPublicClassTimeOption(
            publicClassNote.class,
            publicClassNote.date
        );
        if (result.status == 200) {
            if (result.dataList.length > 0) {
                timeOption.value = result.dataList.map(item => ({
                    value: item,
                    label: item
                }));
            } else {
                showNotify({
                    type: 'warning',
                    message: `当前教室并没有时间提供预约,请选择其他日期或教室`,
                    duration: 8000
                });
                publicClassNote.date = '';
            }
        } else {
            throw new Error(result.message || '公共教室时间获取失败');
        }
    } catch (e) {
        showFailToast(e.message || '公共教室时间获取失败');
    }
};

onMounted(() => {
    getClassOption();
});
</script>

<template>
    <div class="container">
        <h1 class="heading">公共教室预约</h1>
        <div>
            申请人:
            <span class="teacher-name">
                {{ teacherStore.teacherName }}
            </span>
        </div>
        <el-form
            ref="formRef"
            label-position="top"
            class="form-wrapper"
            :rules="formRule"
            :model="publicClassNote"
        >
            <el-form-item label="占用教室" class="form-item" prop="class">
                <el-select
                    v-model="publicClassNote.class"
                    placeholder="请选择教室"
                    class="form-item"
                >
                    <el-option
                        v-for="item in classOption"
                        :label="item"
                        :value="item"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="选择日期" class="form-item" prop="date">
                <el-date-picker
                    class="form-item"
                    v-model="publicClassNote.date"
                    type="date"
                    placeholder="请选择日期"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                />
            </el-form-item>
            <el-form-item label="具体时间" class="form-item" prop="time">
                <el-select-v2
                    :disabled="timeInputDisabled"
                    :placeholder="timeInputPlaceholder"
                    v-model="publicClassNote.time"
                    :options="timeOption"
                    class="form-item"
                    multiple
                ></el-select-v2>
            </el-form-item>
            <el-form-item label="总人数" class="form-item" prop="peopleTotal">
                <el-input-number
                    v-model="publicClassNote.peopleTotal"
                    class="form-item"
                    :min="1"
                ></el-input-number>
            </el-form-item>
            <el-form-item label="教室数量" class="form-item" prop="classTotal">
                <el-input-number
                    v-model="publicClassNote.classTotal"
                    class="form-item"
                    :min="1"
                ></el-input-number>
            </el-form-item>
            <el-form-item label="具体用途" class="form-item" prop="purpose">
                <el-input
                    placeholder="说明具体用途"
                    v-model="publicClassNote.purpose"
                    class="form-item"
                ></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submit(formRef)"
                    >提交申请</el-button
                >
            </el-form-item>
        </el-form>

        <el-dialog
            v-model="isShowDialog"
            width="80%"
            title="申请人承诺"
            align-center
        >
            <p>申请人承诺以上申请事项真实、有效，并承诺本次申请事项:</p>
            <p>一、遵守国家法律法规和学校规章制度;</p>
            <p>二、知晓并遵守相应安全规定;</p>
            <p>三、对所申请事项负责。</p>
            <template #footer>
                <el-button @click="isShowDialog = false">取消</el-button>
                <el-button type="primary" @click="confirm">
                    承诺并确定提交
                </el-button>
            </template>
        </el-dialog>
    </div>
</template>

<style scoped lang="scss">
.container {
    font-size: 16rem;
    padding: 30rem 30rem;
    background-color: rgb(247, 247, 247);

    .heading {
        font-size: 22rem;
        font-weight: bold;
        text-align: center;
        padding-bottom: 20rem;
        margin-bottom: 20rem;
        border-bottom: 1px solid #333;
    }

    .teacher-name {
        font-weight: bold;
    }
}

.form-wrapper {
    margin-top: 20rem;
}

.form-item {
    width: 100%;
}
</style>
